<?php
if(!class_exists('EventManager_Resource_User_Item')){
	require_once dirname(__FILE__) . '/User/Item.php';
}
class EventManager_Model_User extends SF_Model_Acl_Abstract
{
	/**
	 *
	 * @var unknown_type
	 */
	protected $_acl;
	/**
	 *
	 * @param $id
	 * @return unknown_type
	 */
	public function getUserById($id){
		$id = (int) $id;
		return $this->getResource('User')->getUserById($id);
	}
	/**
	 *
	 * @param $email
	 * @param $ignoreUser
	 * @return unknown_type
	 */
	public function getUserByEmail($email, $ignoreUser=null){
		return $this->getResource('User')
		->getUserByEmail($email, $ignoreUser);
	}
	/**
	 *
	 * @param $paged
	 * @param $order
	 * @return unknown_type
	 */
	public function getUsers($paged = false, $order = null){
		return $this->getResource('User')
		->getUsers($paged,$order);
	}
	/**
	 *
	 * @param $post
	 * @return unknown_type
	 */
	public function registerUser($post){
		$form = $this->getForm('userRegister');
		return $this->_save(
		$form,
		$post,
		array('usr_role'=> 'User')
		);
	}
	/**
	 *
	 * @param $post
	 * @return unknown_type
	 */
	public function saveUser($post){
		$form = $this->getForm('userEdit');
		return $this->_save($form,$post);
	}
	/**
	 *
	 * @param Zend_Form $form
	 * @param array $info
	 * @param $defaults
	 * @return unknown_type
	 */
	protected function _save(Zend_Form $form, array $info, $defaults=array()){
		
		/*
                if(!$form->isValid($info)){
                    return false;
		}*/
                
		//get filtered values
		$data = $form->getValues();

		//password hashing
		if(array_key_exists('usr_password',$data) && ''!=$data['usr_password']){
			$data['salt'] = md5($this->createSalt());
			$data['usr_password'] = sha1($data['usr_password'].$data['salt']);
		}else{
			unset($data['usr_password']);
		}
			
		//applay any defaults
		foreach($defaults as $col =>$value){
			$data[$col] = $value;
		}

		$user = array_key_exists('usr_id',$data) ? $this->getResource('User')
		->getUserById($data['usr_id']):null;
		
                return $this->getResource('User')->saveRow($data,$user);

	}
	
	
	public function getUserRights(){
		return $this->getResource('Rights')->getRights();
	}
	/**
	 *
	 * @return unknown_type
	 */
	public function getResourceId(){
		return 'User';
	}
	/**
	 *
	 * @param SF_Acl_Interface $acl
	 * @return unknown_type
	 */
	public function setAcl(SF_Acl_Interface $acl){
		if(!$acl->has($this->getResourceId())){
			$acl->add($this)
			->allow('Guest',$this,array('registerUser','login'))
			->allow('User', $this,array('saveUser','getUsers'))
			->allow('Admin',$this);
		}
		return $this->_acl = $acl;

	}
	/**
	 *
	 * @return unknown_type
	 */
	public function getAcl(){
		if(null === $this->_acl){
			$this->setAcl(new EventManager_Model_Acl_EventManager());
		}
		return $this->_acl;
	}
	/**
	 *
	 * @return unknown_type
	 */
	private function createSalt(){
		$salt = '';
		for($i=0; $i<50; $i++){
			$salt.= chr(rand(33,126));
		}
		return $salt;
	}

}